package xyj.sparrow.scheduler.aop;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xyj.sparrow.scheduler.common.Result;
import xyj.sparrow.scheduler.common.ResultCode;
import xyj.sparrow.scheduler.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * xyj-rpc
 * 权限
 *
 * @author 江南小俊
 * @since 2021-06-07 14:39
 **/

@Aspect
@Slf4j
@Component
public class PermissionsAop {
    @Pointcut("execution(* xyj.sparrow.scheduler.controller.*.*(..))&&@annotation(xyj.sparrow.scheduler.annotation" +
            ".AdminValid)")
    public void admin() {
    }

    @Around(value = "admin()")
    public Object verifyAdmin(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(ResultCode.PERMISSION_DENIED_ERROR);
        }
        try {
            Claims claims = JwtUtil.parseJWT(token);
            ObjectMapper mapper = new ObjectMapper();
        } catch (Exception e) {
            log.error("e", e);
            return Result.error(ResultCode.PERMISSION_DENIED_ERROR);
        }
//        Token tokenObj = mapper.readValue(claims.getSubject(), Token.class);
//        if (tokenObj == null || !"管理员".equals(tokenObj.getRole())) {
////            throw new ResultException(ResultEnum.UNAUTH);
//        }


        return joinPoint.proceed(args);
    }

    @Pointcut("execution(* xyj.sparrow.scheduler.controller.*.*(..))&&@annotation(xyj.sparrow.scheduler.annotation.UserValid)")
    public void user() {
    }

    @Around(value = "user()")
    public Object verifyUser(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            //throw e
            return Result.error(ResultCode.PERMISSION_DENIED_ERROR);
        }
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            log.error("e", e);
            return Result.error(ResultCode.PERMISSION_DENIED_ERROR);
        }
        return joinPoint.proceed(args);
    }
}
